package com.james.customcamera.ui.activity;

import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.james.customcamera.R;
import com.james.customcamera.bean.PhotoBean;
import com.james.customcamera.utils.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

public class PhotoActivity extends AppCompatActivity implements View.OnTouchListener {
    private List<PhotoBean> dataList = new ArrayList<>();
    private int position = 0;
    private GestureDetector mGestureDetector;
    private ImageView photoIv;
    private MediaPlayer mMediaPlayer;

    private static final int FLING_MIN_DISTANCE = 50;   //最小距离
    private static final int FLING_MIN_VELOCITY = 0;  //最小速度

    //线程操作
    private ExecutorService mExecutorService;
    //录音API
    private MediaRecorder mMediaRecorder;
    //录音开始时间与结束时间
    private long startTime, endTime;
    //录音所保存的文件
    private File mAudioFile;
    //录音文件保存位置
    private String mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/audio/";
    //当前是否正在播放
    private volatile boolean isPlaying = false;
    //播放音频文件API
    private MediaPlayer mediaPlayer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        mMediaPlayer = new MediaPlayer();
        dataList = (List<PhotoBean>) getIntent().getExtras().getSerializable("photo_data");
        position = getIntent().getExtras().getInt("photo_position");
        mGestureDetector = new GestureDetector(this, myGestureListener);
        RelativeLayout mRelativeLayout = findViewById(R.id.photo_rl_container);
        mRelativeLayout.setOnTouchListener(this);
        mRelativeLayout.setLongClickable(true);
        loadPhoto(position);
    }

    private void loadPhoto(int position) {
        Glide.with(getApplicationContext())
                .load(dataList.get(position).getPictureFileUrl())
                .error(R.mipmap.ic_launcher)
                .into(photoIv);
    }

    GestureDetector.SimpleOnGestureListener myGestureListener = new GestureDetector.SimpleOnGestureListener() {
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

            Log.e("<--滑动测试-->", "开始滑动");
            float x = e1.getX() - e2.getX();
            float x2 = e2.getX() - e1.getX();
            if (x > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
                Toast.makeText(getApplicationContext(), "向左手势", Toast.LENGTH_SHORT).show();
                if (position == 0) {
                    ToastUtils.showShortToastCenter("前面已没有照片！");
                } else {
                    playEndOrFail();
                    position--;
                    loadPhoto(position);
                    //播放声音
                    playAudio(dataList.get(position).getSoundFileUrl());
                }
                //startActivity(new Intent(HuadongTestActivity.this, HuadongOtherActivity.class));

            } else if (x2 > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
                Toast.makeText(getApplicationContext(), "向右手势", Toast.LENGTH_SHORT).show();
                if (position < dataList.size()) {
                    playEndOrFail();
                    position++;
                    loadPhoto(position);
                    //播放声音
                    playAudio(dataList.get(position).getSoundFileUrl());
                } else {
                    ToastUtils.showShortToastCenter("后面已没有照片！");
                }
            }

            return false;
        }

    };


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //页面销毁，线程要关闭
        mExecutorService.shutdownNow();
    }

    /**
     * @description 播放音频
     * @author ldm
     * @time 2017/2/9 16:54
     */
    private void playAudio(final String audioUrl) {
        if (null != audioUrl && !isPlaying) {
            isPlaying = true;
            mExecutorService.submit(new Runnable() {
                @Override
                public void run() {
                    startPlay(audioUrl);
                }
            });
        }
    }

    /**
     * @description 开始播放音频文件
     * @author ldm
     * @time 2017/2/9 16:56
     */
    private void startPlay(String audioUrl) {
        try {
            isPlaying = true;
            //初始化播放器
            mediaPlayer = new MediaPlayer();
            //设置播放音频数据文件
            mediaPlayer.setDataSource(audioUrl);
            //设置播放监听事件
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    //播放完成
                    playEndOrFail();
                }
            });
            //播放发生错误监听事件
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    playEndOrFail();
                    return true;
                }
            });
            //播放器音量配置
            mediaPlayer.setVolume(1, 1);
            //是否循环播放
            mediaPlayer.setLooping(false);
            //准备及播放
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
            //播放失败正理
            playEndOrFail();
        }

    }

    /**
     * @description 停止播放或播放失败处理
     * @author ldm
     * @time 2017/2/9 16:58
     */
    private void playEndOrFail() {
        isPlaying = false;
        if (null != mediaPlayer) {
            mediaPlayer.setOnCompletionListener(null);
            mediaPlayer.setOnErrorListener(null);
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
